package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    public static final String EXCHANGE = "stock-event-exchange";
    public static final String NORMAL_QUEUE = "stock.delay.queue";
    public static final String DEAD_QUEUE = "stock.release.stock.queue";
    public static final String NORMAL_ROUTINGKEY = "stock.locked";
    public static final String DEAD_ROUTINGKEY = "stock.release";
    public static final Integer MESSAGE_TTL = 120000;

    @Bean
    public TopicExchange exchange() {
        TopicExchange topicExchange = new TopicExchange(EXCHANGE, true, false);
        return topicExchange;
    }

    @Bean
    public Queue normalQUeue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", EXCHANGE);
        arguments.put("x-dead-letter-routing-key", DEAD_ROUTINGKEY);
        arguments.put("x-message-ttl", MESSAGE_TTL);
        return QueueBuilder.durable(NORMAL_QUEUE).withArguments(arguments).build();
    }

    @Bean
    public Queue deadQueue() {
        return QueueBuilder.durable(DEAD_QUEUE).build();
    }

    @Bean
    public Binding normalBinding() {
        return BindingBuilder.bind(normalQUeue()).to(exchange()).with(NORMAL_ROUTINGKEY);
    }

    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(exchange()).with(DEAD_ROUTINGKEY);
    }
}
